<template>
  <div class="process">
    <el-col :span="6">
      <div class="grid-content bg-purple">
        <el-table
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          style="width: 100%;cursor: pointer;border-left: #efeded 1px solid;border-right: #c7cbd0 10px solid"
          :highlight-current-row="curRow"
          @current-change="changeSelection"
        >
          <el-table-column
            label="工序单元"
            prop="processName">
          </el-table-column>
          <el-table-column
            align="right">
            <template slot="header" slot-scope="scope">
              <el-button
                size="mini"
                @click="showAddProcessDialog(scope.$index, scope.row)">+
              </el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="normal"
                icon="el-icon-delete"
                @click="handleDeleteProcess(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-col>
    <el-col :span="18">
      <el-table
        :data="emissionData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
        style="width: 100%;border-left: #c7cbd0 1px solid">
        <el-table-column
          label="能源材料"
          prop="name">
        </el-table-column>
        <el-table-column
          label="排放阶段"
          prop="produceStage">
        </el-table-column>
        <el-table-column
          align="right">
          <template slot="header" slot-scope="scope">
            <el-button
              v-if="!curRow"
              size="mini"
              @click="showAddEmissionOriginDialog(scope.$index, scope.row)" disabled>+
            </el-button>
            <el-button
              v-if="curRow"
              size="mini"
              @click="showAddEmissionOriginDialog(scope.$index, scope.row)">+
            </el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="normal"
              icon="el-icon-edit"
              @click="handleEditEmission(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="normal"
              icon="el-icon-delete"
              @click="handleDeleteEmission(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>

    <el-dialog title="添加工序" :visible.sync="addProcessDialog">
      <el-form :model="addProcessForm" :rules="rulesForm">
        <el-form-item label="工序名称" :label-width="formLabelWidth" prop="processName">
          <el-input v-model="addProcessForm.processName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addProcessDialog = false">取 消</el-button>
        <el-button type="danger" @click="submitAddProcess">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="添加能源材料" :visible.sync="addEmissionOriginDialog">
      <el-form :model="addEmissionOriginForm" :rules="rulesForm">
        <el-form-item label="能源名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addEmissionOriginForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="生产阶段" :label-width="formLabelWidth" prop="stages">
          <el-select v-model="addEmissionOriginForm.selectStages" multiple placeholder="请选择" @change="changeStages">
            <el-option
              v-for="item in stages"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addEmissionOriginDialog = false">取 消</el-button>
        <el-button type="danger" @click="submitAddEmissionOrigin">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑能源材料" :visible.sync="editEmissionDialog">
      <el-form :model="editEmissionForm" :rules="rulesForm">
        <el-form-item label="能源名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="editEmissionForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="生产阶段" :label-width="formLabelWidth" prop="stages">
          <el-select v-model="editEmissionForm.stageList" multiple placeholder="请选择"
                     @change="changeEmissionStages">
            <el-option
              v-for="item in emissionStages"
              :key="item.id"
              :label="item.stage"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addEmissionOriginDialog = false">取 消</el-button>
        <el-button type="danger" @click="submitEditEmissionOrigin">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  addEmissionOrigin,
  addProcess,
  deleteProcess, editEmissionOrigin,
  queryAllProcess,
  queryEmissionOriginDetail
} from "@/api/carbon-manage/process";
import {deleteEmissionOrigin} from "@/api/carbon-manage/emission_origin";
import {listStage} from "@/api/carbon-manage/data";

export default {
  name: "News",
  data() {
    return {
      tableData: [],
      emissionData: [],
      search: '',
      curRow: false,
      emissionVisible: false,
      processVisible: false,
      curSelectProcessId: '',
      addProcessDialog: false,
      addEmissionOriginDialog: false,
      addEmissionOriginForm: {
        name: '',
        selectStages: [],
        processId: '',
      },
      addProcessForm: {
        processName: ""
      },
      editEmissionForm: {
        name: "",
        stageList: [],
      },
      editEmissionDialog: false,
      stages: [],
      emissionStages: [],
      formLabelWidth: '90px',

      rulesForm: {
        processName: [
          {required: true, message: '请输入工序名称', trigger: 'blur'},
        ],
        stages: [
          {required: true, message: '请输入工序名称', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入能源名称', trigger: 'blur'},
        ],
      },

    };
  },
  created() {
    this.queryAllStages()
    this.loadData();
  },
  methods: {
    submitEditEmissionOrigin() {
      editEmissionOrigin(this.editEmissionForm).then(res => {
        if (res.code === 200) {
          this.$message.success('编辑成功');
          this.editEmissionDialog = false;
          this.loadData()
        }
      })
    },
    changeEmissionStages(item) {
      this.editEmissionForm.stageList = item
      this.$forceUpdate();
    },
    changeStages(items) {
      this.addEmissionOriginForm.processId = this.curSelectProcessId;
    },
    queryAllStages() {
      listStage().then(res => {
        if (res.code === 200) {
          this.stages = res.data;
          this.emissionStages = this.stages.map(item => {
            return {
              id: item.id,
              stage: item.name
            }
          });
        }
      })
    },
    async loadData() {
      await queryAllProcess().then(res => {
        console.log(res)
        if (res.code === 200) {
          this.tableData = res.data
        }
      });
      await this.changeSelection();
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDeleteProcess(index, row) {
      this.$confirm('是否删除该工序数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProcess(row.processId).then(response => {
          console.log(response)
          if (response.code === 200) {
            this.$message.success('删除成功');
            this.loadData()
          }
        })
      })
    },
    handleDeleteEmission(index, row) {
      this.$confirm('是否删除该能源材料?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row.id, this.curSelectProcessId)
        deleteEmissionOrigin(this.curSelectProcessId, row.id).then(response => {
          if (response.code === 200) {
            this.$message.success('删除成功');
            this.loadData()
          }
        })
      })
    },
    changeSelection(data) {
      for (let i = 0; i < this.tableData.length; i++) {
        let data = this.tableData[i];
        if (data.processId === this.curSelectProcessId) {
          this.emissionData = data.emissionOriginList;
          break;
        }
      }

      if (data) {
        this.curSelectProcessId = data.processId;
        this.emissionData = data.emissionOriginList;
        this.emissionData.map(item => {
          let arr = []
          try {
            arr = JSON.parse(item.produceStage);
          } catch (error) {
            return;
          }
          arr = JSON.parse(item.produceStage);
          let stage = '';
          for (let i = 0; i < arr.length; i++) {
            if (arr[i] === 1) {
              stage += '燃料燃烧'
            } else if (arr[i] === 2) {
              stage += '，工业生产'
            } else if (arr[i] === 3) {
              stage += '，电力热力'
            } else if (arr[i] === 4) {
              stage += '，固碳产品'
            }
          }
          if (stage.slice(0, 1) === '，') {
            stage = stage.substring(1);
          }
          item.produceStage = stage;
        });
        this.curRow = true;
      } else {
        this.emissionData.map(item => {
          let arr = []
          try {
            arr = JSON.parse(item.produceStage);
          } catch (error) {
            return;
          }
          let stage = '';
          for (let i = 0; i < arr.length; i++) {
            if (arr[i] === 1) {
              stage += '燃料燃烧'
            } else if (arr[i] === 2) {
              stage += '，工业生产'
            } else if (arr[i] === 3) {
              stage += '，电力热力'
            } else if (arr[i] === 4) {
              stage += '，固碳产品'
            }
          }
          if (stage.slice(0, 1) === '，') {
            stage = stage.substring(1);
          }
          item.produceStage = stage;
        })
      }
    },
    showAddProcessDialog(index, row) {
      this.addProcessDialog = true;
      this.addProcessForm = {};
    },
    showAddEmissionOriginDialog(index, row) {
      this.addEmissionOriginDialog = true;
      this.addEmissionOriginForm = {};
    },
    submitAddProcess() {
      if (!this.addProcessForm.processName) {
        return;
      }
      addProcess(this.addProcessForm).then(res => {
        if (res.code === 200) {
          this.loadData();
          this.addProcessForm = {}
          this.addProcessDialog = false;
        }
      })
    },
    submitAddEmissionOrigin() {
      if (!this.addEmissionOriginForm.name) {
        return;
      }
      if (this.addEmissionOriginForm.selectStages.length === 0) {
        return;
      }
      addEmissionOrigin(this.addEmissionOriginForm).then(res => {
        if (res.code === 200) {
          this.addEmissionOriginDialog = false;//[272,284,290,294]
          this.addEmissionOriginForm = {};
          this.loadData();
          this.$message.success('能源材料添加成功');
        }
      });
    },
    handleEditEmission(index, row) {
      this.editEmissionDialog = true;
      console.log(row)
      queryEmissionOriginDetail(row.id).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.editEmissionForm = res.data
          this.editEmissionForm.stageList = res.data.stageVoList.map(item => {
            return item.id;
          });
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
.process {
  margin: 10px;
}

</style>
